﻿using Daneas.Utility.Data;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
using System.Xml;

namespace Daneas.Utility.Universals
{
    /// <summary>
    /// 未完成，不可使用
    /// </summary>
    public class CodeGeneartorMysql
    {
        private static string mysqldb = ConfigurationManager.AppSettings["mydb"].ToString();
        #region 生成路径配置
        private static string rootPath = ConfigurationManager.AppSettings["MyBaseCodePath"].ToString();
        private static string ModelNameSpace = ConfigurationManager.AppSettings["MyModelNameSpace"].ToString();
        private static string DALNameSpace = ConfigurationManager.AppSettings["MyDALNameSpace"].ToString();

        private static string projPath = rootPath + "MyBaseCode/MyBaseCode.csproj";
        private static string modelPath = rootPath + "MyBaseCode/Model";
        private static string baseDalPath = rootPath + "MyBaseCode/BaseDAL";
        #endregion

        private readonly string tablesSql = "select table_name from information_schema.tables where table_schema='{0}'";

        private readonly string colunmsSql =
            "select column_name name,data_type type,COLUMN_TYPE,column_comment as info,extra as auto,CHARACTER_MAXIMUM_LENGTH as len " +
            "from INFORMATION_SCHEMA.COLUMNS Where table_name ='{0}' and table_schema ='{1}'";


        #region 代码生成

        public bool CreateBaseCode()
        {
            try
            {
                DataTable dt = MySqlHelper.ExecutQuery(string.Format(tablesSql, mysqldb)).Tables[0];

                try
                {
                    CreateModels(dt);
                }
                catch
                { }

                try
                {
                    CreateBaseDAL(dt);
                }
                catch
                { }

                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool CreateModels()
        {
            DataTable dt = MySqlHelper.ExecutQuery(string.Format(tablesSql, mysqldb)).Tables[0];

            CreateModels(dt);

            return true;
        }

        public bool CreateBaseDAL()
        {
            DataTable dt = MySqlHelper.ExecutQuery(string.Format(tablesSql, mysqldb)).Tables[0];

            CreateBaseDAL(dt);

            return true;
        }

        /// <summary>
        /// 生成Model
        /// </summary>
        /// <param name="dt">对象表</param>
        /// <remarks>//0.表名；1.字段序号；2.字段名；3.标示；4.主键；5.类型；6.占用字节长度；7.小数位数；8.允许空；9.默认值；10.字段说明</remarks>
        /// <returns></returns>
        private bool CreateModels(DataTable dt)
        {
            if (dt.Rows.Count < 1)
            {
                return true;
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string tableName = dt.Rows[i]["table_name"].ToString();
                DataTable dc = MySqlHelper.ExecutQuery(string.Format(colunmsSql, tableName, mysqldb)).Tables[0];
                int count = dc.Rows.Count;

                if (count < 1)
                {
                    continue;
                }
                //0.表名；1.字段类型；2.字段类型（全）；3.标示；4.主键；5.默认长度；
                //重写商城的时候使用
                string csname = tableName.Replace("33hao_", "tcg_");

                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < count; j++)
                {
                    var fliedname = dc.Rows[j]["name"].ToString();
                    var fliedtype = dc.Rows[j]["type"].ToString();
                    var columtype = dc.Rows[j]["COLUMN_TYPE"].ToString();

                    if (!string.IsNullOrWhiteSpace(fliedname))
                    {
                        sb.Append("\r\t/// <summary>");
                        sb.Append("\r\t/// " + dc.Rows[j]["info"] + "【" + dc.Rows[j]["auto"] + "】【" + fliedtype + "】【长度：" + dc.Rows[j]["len"] + "】【类型：" + columtype + "】");
                        sb.Append("\r\t/// </summary>");
                    }
                    if (columtype == "tinyint(1)")
                    {
                        sb.Append("\r\tpublic bool " + fliedname + "{ get; set; }\n");
                    }
                    else
                    {
                        sb.Append("\r\tpublic " + GetFiledType(fliedtype) + " " + fliedname + "{ get; set; }\n");
                    }
                }

                StringBuilder model = new StringBuilder();
                model.Append("using System;\r\n");
                model.Append("using Daneas.Utility.Data;\r\n");
                model.Append("\r\n");
                model.Append("namespace " + ModelNameSpace + " \r\n");
                model.Append("{\r\n");
                model.Append("/// <summary>\r\n");
                model.AppendFormat("/// {0}:实体类\r\n", tableName);
                model.Append("/// </summary>\r\n");
                model.Append("[Serializable]\r\n");
                model.AppendFormat("public partial class {0}\r\n", csname);
                model.Append("{\r\n");
                model.Append(sb.ToString());
                model.Append("}\r\n");
                model.Append("}\r\n");

                WriteToModels(csname, model.ToString());
            }

            return true;
        }

        /// <summary>
        /// 生成DAL的基础方法
        /// </summary>
        /// <param name="dt">对象表</param>
        /// <remarks>//0.表名；1.字段序号；2.字段名；3.标示；4.主键；5.类型；6.占用字节长度；7.小数位数；8.允许空；9.默认值；10.字段说明</remarks>
        /// <returns></returns>
        private bool CreateBaseDAL(DataTable dt)
        {
            if (dt.Rows.Count < 1)
            {
                return true;
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string tableName = dt.Rows[i]["table_name"].ToString();
                DataTable dc = MySqlHelper.ExecutQuery(string.Format(colunmsSql, tableName, mysqldb)).Tables[0];
                int count = dc.Rows.Count;

                if (count < 1)
                {
                    continue;
                }

                //0.表名；1.字段类型；2.字段类型（全）；3.标示；4.主键；5.默认长度；         

                //重写商城的时候使用
                string csname = tableName.Replace("33hao_", "tcg_");

                StringBuilder model = new StringBuilder();
                model.Append("using MySql.Data.MySqlClient;\r\n");
                model.Append("using System.Collections.Generic;\r\n");
                model.Append("using System.Data;\r\n");
                model.Append("using System;\r\n");
                model.Append("using " + ModelNameSpace + ";\r\n");
                model.Append("\r\n");
                model.Append("namespace " + DALNameSpace + " \r\n");
                model.Append("{\r\n");
                model.Append("\r\t/// <summary>");
                model.AppendFormat("\r\t/// {0}:基础数据操作类", tableName);
                model.Append("\r\t/// </summary>\r\n");
                model.AppendFormat("\r\tpublic partial class {0}DAL", csname);
                model.Append("\r\t{");
                model.Append("\r\t\tpublic static string dbconn = DBConn.connStr;");

                if ((dc.Rows[0]["type"].ToString() == "mediumint"
                    || dc.Rows[0]["type"].ToString() == "int")
                    && dc.Rows[0]["auto"].ToString() == "auto_increment")
                {
                    model.Append(GetItem(dc, tableName, csname));
                    model.Append("\r\n");

                    model.Append(DeleteItem(dc, tableName, csname));
                    model.Append("\r\n");

                    model.Append(UpdateItem(dc, tableName, csname));
                    model.Append("\r\n");
                }

                model.Append(Create(dc, tableName, csname));
                model.Append("\r\n");
                model.Append(Query(dc, tableName, csname));
                model.Append("\r\n");
                model.Append(QueryItems(dc, tableName, csname));
                model.Append("\r\n");
                model.Append(GetBind(dc, tableName, csname));
                model.Append("\r\n");
                model.Append("\r\t}");
                model.Append("\r}");

                WriteToDals(csname, model.ToString());

            }

            return true;
        }


        /// <summary>
        /// 一般和事务新增
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private static string Create(DataTable dt, string tablename, string csname)
        {
            StringBuilder Sb = new StringBuilder();
            var count = dt.Rows.Count;

            Sb.Append("\r\rpublic bool Insert(" + csname + " model)");
            Sb.Append("\n{\n");

            string sql = "insert into " + tablename + "(";
            string paras = "";
            for (int i = 0; i < count; i++)
            {
                if (dt.Rows[i]["auto"].ToString() == "auto_increment")
                {
                    continue;
                }
                var fliedname = dt.Rows[i]["name"].ToString();
                sql += fliedname + ",";
                paras += "@" + fliedname + ",";
            }
            sql = sql.TrimEnd(',') + ")";
            paras = paras.TrimEnd(',');
            sql += " values (" + paras + ")";


            Sb.Append("string sql=\"" + sql + "\";");
            Sb.Append("\r\t\tMySqlParameter[] parameters = {");
            #region 条件
            int c = 0;
            string conndetion = "";
            for (int i = 0; i < count; i++)
            {
                if (dt.Rows[i]["auto"].ToString() == "auto_increment")
                {
                    continue;
                }
                var fliedname = dt.Rows[i]["name"].ToString();
                var fliedtype = dt.Rows[i]["type"].ToString();
                var fliedlen = (dt.Rows[i]["len"] ?? "").ToString();
                #region 参数

                string len = "";
                if (!string.IsNullOrWhiteSpace(fliedlen))
                {
                    len += "," + fliedlen;
                }
                Sb.Append("\r\t new MySqlParameter(\"@" + fliedname + "\", " + GetSqlType(fliedtype) + len + ")");
                Sb.Append(",");
                conndetion += "\rparameters[" + c++ + "].Value = model." + fliedname + ";";

                #endregion
            }
            string strSb = Sb.ToString().TrimEnd(',');
            Sb = new StringBuilder(strSb);
            #endregion
            Sb.Append("\r\t\t\t\t};");
            Sb.Append(conndetion);
            Sb.Append("\rreturn MySqlHelper.ExecuteNonQuery(dbconn,sql,parameters)>0;");
            Sb.Append("\n}\n");



            return Sb.ToString();
        }

        private static string Query(DataTable dt, string tablename, string csname)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("\r\n    /// <summary>;");
            sb.Append("\r\n     /// ;");
            sb.Append("\r\n   /// </summary>;");
            sb.Append("\r\n    /// <param name=\"count\">返回总数</param>");
            sb.Append("\r\n    /// <param name=\"dic1\">或条件</param>");
            sb.Append("\r\n    /// <param name=\"dic2\">并条件</param>");
            sb.Append("\r\n    /// <param name=\"pageindex\">页码</param>");
            sb.Append("\r\n    /// <param name=\"pagesize\">页面大小</param>");
            sb.Append("\r\n    /// <returns></returns>");
            sb.Append("\r\n public DataSet GetList(Dictionary<string, object> dic1, Dictionary<string, object> dic2,string orderby, int pageindex, int pagesize)");
            sb.Append("\r\n  {");
            sb.Append("\r\n     int startrow = pageindex < 1 ? 0 : (pageindex - 1) * pagesize;");
            sb.Append("\r\n     pagesize = pagesize < 1 ? 10 : pagesize;");
            sb.Append("\r\n     orderby = orderby == null? \"\" : orderby;");
            sb.Append("\r\n     List<MySqlParameter> paramList = new List<MySqlParameter>();\r\n");

            sb.Append("\r\n     string sql = \" from " + tablename + " where 1 = 1 \";");
            //或关系
            sb.Append("   if(dic1!=null&&dic1.Count>0){ \r\n");
            sb.Append("   int i=0; \r\n");
            sb.Append("   sql+=\" And (\"; \r\n");
            sb.Append("   foreach (var item in dic1) \r\n");
            sb.Append("   { \r\n");
            sb.Append("      if(i==0){ \r\n");
            sb.Append("           sql += item.Key + \" LIKE '%'+ @\" + item.Key+\" + '%'\";} \r\n");
            sb.Append("      else{  sql += \" Or \" + item.Key + \" LIKE '%'+ @\" + item.Key+\" + '%'\";} \r\n");
            sb.Append("      paramList.Add(new MySqlParameter(\"@\" + item.Key, item.Value)); \r\n");
            sb.Append("      i+=1;\r\n");
            sb.Append("   } \r\n");
            sb.Append("   sql+=\")\"; \r\n");
            sb.Append("   } \r\n");
            sb.Append("  \r\n");

            //且关系
            sb.Append("   if(dic2!=null&&dic2.Count>0){ \r\n");
            sb.Append("   foreach (var item in dic2) \r\n");
            sb.Append("   { \r\n");
            sb.Append("       sql += \" And \" + item.Key + \"=@\" + item.Key; \r\n");
            sb.Append("       paramList.Add( new MySqlParameter(\"@\" + item.Key, item.Value)); \r\n");
            sb.Append("   } \r\n");
            sb.Append("   } \r\n");
            sb.Append("  \r\n");

            sb.Append("\r\n     string sql1 = \"select * \" + sql + (orderby.Length>0 ? \" order by \" + orderby : \"\");");

            sb.Append("\r\n     string sql2 = sql1 + \" limit \" + startrow + \", \" + pagesize + \"; \";");

            sb.Append("\r\n     string sql3 = \"select count(*) \" + sql + \";\";");

            sb.Append("\r\n     string query = sql2 + sql3;");

            sb.Append("\r\n     return MySqlHelper.ExecuteDataset(dbconn,query,paramList.ToArray());");
            sb.Append("\r\n  }");

            return sb.ToString();
        }

        private static string QueryItems(DataTable dt, string tablename, string csname)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("\r\n    /// <summary>;");
            sb.Append("\r\n     /// ;");
            sb.Append("\r\n   /// </summary>;");
            sb.Append("\r\n    /// <param name=\"dic1\">且关系</param>");
            sb.Append("\r\n    /// <returns>返回符合条件的items</returns>");
            sb.Append("\r\n public List<" + csname + ">  GetList(Dictionary<string, object> dic1)");
            sb.Append("\r\n  {");
            sb.Append("\r\n     List<MySqlParameter> paramList = new List<MySqlParameter>();\r\n");
            sb.Append("\r\n     string sql = \"select * from " + tablename + " where 1 = 1\";\r\n");


            //且关系
            sb.Append("   if(dic1!=null&&dic1.Count>0){ \r\n");
            sb.Append("   foreach (var item in dic1) \r\n");
            sb.Append("   { \r\n");
            sb.Append("       sql += \" And \" + item.Key + \"=@\" + item.Key; \r\n");
            sb.Append("       paramList.Add( new MySqlParameter(\"@\" + item.Key, item.Value)); \r\n");
            sb.Append("   } \r\n");
            sb.Append("   } \r\n");
            sb.Append("  \r\n");

            sb.Append("\r\tDataTable dt = MySqlHelper.ExecuteDataset(dbconn,sql,paramList.ToArray()).Tables[0];");
            sb.Append("\r\tif(dt==null||dt.Rows.Count<1){return null;}");
            sb.Append("\r\treturn ReaderBinds(dt);");
            sb.Append("\r\n  }");

            //那个啥，内部使用where

            sb.Append("\r\n public List<" + csname + ">  GetConditions(string condition)");
            sb.Append("\r\n  {");
            sb.Append("\r\t\tstring sql = \"select * from " + tablename + " where \" + condition;\r\n");
            sb.Append("\r\tDataTable dt = MySqlHelper.ExecuteDataset(dbconn,sql).Tables[0];");
            sb.Append("\r\tif(dt==null||dt.Rows.Count<1){return null;}");
            sb.Append("\r\treturn ReaderBinds(dt);");
            sb.Append("\r\n  }");
            

            return sb.ToString();
        }

        private static string GetItem(DataTable dt, string tablename, string csname)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("\r\t\t/// <summary>;");
            sb.Append("\r\t\t/// ;");
            sb.Append("\r\t\t/// </summary>;");
            sb.Append("\r\t\t/// <param name=\"id\">id</param>");
            sb.Append("\r\t\t/// <returns>返回符合条件的item</returns>");
            sb.Append("\r\t\tpublic " + csname + "  GetById(int id)");
            sb.Append("\r\t\t{");
            sb.Append("\r\t\t\tstring sql = \"select * from " + tablename + " where 1 = 1\";");
            sb.Append("\r\t\t\tsql += \" And " + dt.Rows[0]["name"] + "=@" + dt.Rows[0]["name"] + "\"; ");
            sb.Append("\r\t\t\tMySqlParameter para= new MySqlParameter(\"@" + dt.Rows[0]["name"] + "\" , id); ");
            sb.Append("\r\n");
            sb.Append("\r\t\t\tDataTable dt = MySqlHelper.ExecuteDataset(dbconn,sql,para).Tables[0];");
            sb.Append("\r\t\t\tif(dt==null||dt.Rows.Count<1){return null;}");
            sb.Append("\r\t\t\treturn ReaderBind(dt.Rows[0]);");
            sb.Append("\r\t\t}");

            return sb.ToString();
        }

        private static string GetBind(DataTable dt, string tablename, string csname)
        {
            StringBuilder Sb = new StringBuilder();
            var count = dt.Rows.Count;
            Sb.Append("\r\t\tpublic " + csname + " ReaderBind(DataRow dr)");
            Sb.Append("\r\t\t{");
            Sb.Append("\r\t\t\t" + csname + " model = new " + csname + "();");
            for (int i = 0; i < count; i++)
            {
                var fliedname = dt.Rows[i]["name"].ToString();
                var fliedtype = dt.Rows[i]["type"].ToString();
                var columtype = dt.Rows[i]["COLUMN_TYPE"].ToString();

                if (fliedtype.ToLower() == "varchar"
                    || fliedtype.ToLower() == "text"
                    || fliedtype.ToLower() == "char"
                    || fliedtype.ToLower() == "blob"
                    || fliedtype.ToLower() == "mediumtext"
                    || fliedtype.ToLower() == "mediumblob"
                    || fliedtype.ToLower() == "tinyblob"
                    || fliedtype.ToLower() == "tinytext"
                    || fliedtype.ToLower() == "longblob"
                    || fliedtype.ToLower() == "longtext")
                {
                    Sb.Append("\r\t\t\tmodel." + fliedname + "=dr[\"" + fliedname + "\"].ToString();");
                }
                else
                {
                    if (columtype == "tinyint(1)")
                    {
                        Sb.Append("\r\t\t\tmodel." + fliedname + "=bool.Parse(dr[\"" + fliedname + "\"].ToString()==\"\"?\"" + GetDefualt(fliedtype) + "\":dr[\"" + fliedname + "\"].ToString());");
                    }
                    else
                    {
                        Sb.Append("\r\t\t\tmodel." + fliedname + "=" + GetFiledType(fliedtype) + ".Parse(dr[\"" + fliedname + "\"].ToString()==\"\"?\"" + GetDefualt(fliedtype) + "\":dr[\"" + fliedname + "\"].ToString());");
                    }
                }
            }
            Sb.Append("\r\t\t\treturn model;");
            Sb.Append("\r\t\t}");

            //列表

            Sb.Append("\r\t\tpublic List<" + csname + "> ReaderBinds(DataTable dt)");
            Sb.Append("\r\t\t{");
            Sb.Append("\r\t\t\t List<" + csname + ">  list=new List<" + csname + ">();");
            Sb.Append("\r\t\t\t foreach(DataRow dr in dt.Rows)");
            Sb.Append("\r\t\t\t{");
            Sb.Append("\r\t\t\t" + csname + " model = new " + csname + "();");
            for (int i = 0; i < count; i++)
            {
                var fliedname = dt.Rows[i]["name"].ToString();
                var fliedtype = dt.Rows[i]["type"].ToString();
                var columtype = dt.Rows[i]["COLUMN_TYPE"].ToString();

                if (fliedtype.ToLower() == "varchar"
                    || fliedtype.ToLower() == "text"
                    || fliedtype.ToLower() == "char"
                    || fliedtype.ToLower() == "blob"
                    || fliedtype.ToLower() == "mediumtext"
                    || fliedtype.ToLower() == "mediumblob"
                    || fliedtype.ToLower() == "tinyblob"
                    || fliedtype.ToLower() == "tinytext"
                    || fliedtype.ToLower() == "longblob"
                    || fliedtype.ToLower() == "longtext")
                {
                    Sb.Append("\r\t\t\tmodel." + fliedname + "=dr[\"" + fliedname + "\"].ToString();");
                }
                else
                {
                    if (columtype == "tinyint(1)")
                    {
                        Sb.Append("\r\t\t\tmodel." + fliedname + "=bool.Parse(dr[\"" + fliedname + "\"].ToString()==\"\"?\"" + GetDefualt(fliedtype) + "\":dr[\"" + fliedname + "\"].ToString());");
                    }
                    else
                    {
                        Sb.Append("\r\t\t\tmodel." + fliedname + "=" + GetFiledType(fliedtype) + ".Parse(dr[\"" + fliedname + "\"].ToString()==\"\"?\"" + GetDefualt(fliedtype) + "\":dr[\"" + fliedname + "\"].ToString());");
                    }
                }

            }
            Sb.Append("\r\t\t\tlist.Add(model);");

            Sb.Append("\r\t\t}");

            Sb.Append("\r\t\t\treturn list;");
            Sb.Append("\r\t\t}");

            return Sb.ToString();
        }

        private static string DeleteItem(DataTable dt, string tablename, string csname)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("\r\t\t/// <summary>;");
            sb.Append("\r\t\t/// 删除item");
            sb.Append("\r\t\t/// </summary>;");
            sb.Append("\r\t\t/// <param name=\"id\">id</param>");
            sb.Append("\r\t\t/// <returns>bool</returns>");
            sb.Append("\r\t\tpublic bool DeleteById(int id)");
            sb.Append("\r\t\t{");
            sb.Append("\r\t\t     string sql = \"delete from " + tablename + " where 1 = 1\";\r\n");
            sb.Append("\r\t\t     sql += \" And " + dt.Rows[0]["name"] + "=@" + dt.Rows[0]["name"] + "\"; ");
            sb.Append("\r\t\t     MySqlParameter para= new MySqlParameter(\"@" + dt.Rows[0]["name"] + "\" , id); ");
            sb.Append("\r\t\t     return MySqlHelper.ExecuteNonQuery(dbconn,sql,para)>0;");
            sb.Append("\r\t\t}");

            return sb.ToString();
        }
        
        private static string UpdateItem(DataTable dt, string tablename, string csname)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("\r\t\t/// <summary>;");
            sb.Append("\r\t\t/// ;");
            sb.Append("\r\t\t/// </summary>;");
            sb.Append("\r\t\t/// <param name=\"dic1\">字段，条件</param>");
            sb.Append("\r\t\t/// <returns>更新符合条件的item</returns>");
            sb.Append("\r\t\tpublic bool UpdateItem(int id,Dictionary<string, object> dic1)");
            sb.Append("\r\t\t{");
            sb.Append("\r\t\t       string sql = \"update " + tablename + " set \";");
            //且关系
            sb.Append("\r\t\t       List<MySqlParameter> paramList = new List<MySqlParameter>();");
            sb.Append("\r\t\t       if(dic1!=null&&dic1.Count>0){ ");
            sb.Append("\r\t\t       foreach (var item in dic1)");
            sb.Append("\r\t\t       {");
            sb.Append("\r\t\t           sql += \" And \" + item.Key + \"=@\" + item.Key;");
            sb.Append("\r\t\t           paramList.Add( new MySqlParameter(\"@\" + item.Key, item.Value));");
            sb.Append("\r\t\t       }");
            sb.Append("\r\t\t   }");
            sb.Append("\r\t\t   sql+=\"where " + dt.Rows[0]["name"] + "=@" + dt.Rows[0]["name"] + "\";");
            sb.Append("\r\t\t   paramList.Add(new MySqlParameter(\"@" + dt.Rows[0]["name"] + "\" , id)); ");
            sb.Append("\r\t\t   return MySqlHelper.ExecuteNonQuery(dbconn,sql,paramList.ToArray())>0;");
            sb.Append("\r\t\t}");

            return sb.ToString();
        }
        #endregion

        #region 写入文件


        /// <summary>
        /// 保存model
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        /// <summary>
        /// 保存model
        /// </summary>
        /// <param name="path"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private static bool WriteToModels(string tableName, string code)
        {
            string modeDir = modelPath;

            if (!Directory.Exists(modeDir))
            {
                Directory.CreateDirectory(modeDir);
            }

            string filePath = modeDir + "/" + tableName + ".cs";

            if (File.Exists(filePath))
            {
                File.Delete(filePath);

            }

            using (StreamWriter sw = File.AppendText(filePath)) //写
            {
                sw.WriteLine(code);
            }

            WriteToProj("Model\\" + tableName + ".cs");

            return true;
        }

        /// <summary>
        /// 保存dal基础方法
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private static bool WriteToDals(string tableName, string code)
        {
            string baseDalDir = baseDalPath;

            if (!Directory.Exists(baseDalDir))
            {
                Directory.CreateDirectory(baseDalDir);
            }

            string filePath = baseDalDir + "/" + tableName + "BaseDAL.cs";

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }


            using (StreamWriter sw = File.AppendText(filePath)) //写
            {
                sw.WriteLine(code);
            }

            WriteToProj("BaseDAL\\" + tableName + "BaseDAL.cs");

            return true;
        }

        /// <summary>
        /// 给basecode项目文件写东西
        /// </summary>
        /// <param name="path">cs地址</param>
        private static void WriteToProj(string csPath)
        {
            string data = "";

            using (StreamReader sr = File.OpenText(projPath))
            {
                data = sr.ReadToEnd();
            }

            XmlDocument xml = new XmlDocument();

            xml.LoadXml(data);

            if (xml.HasChildNodes)
            {
                XmlNode root = xml.LastChild;
                foreach (XmlNode node in root)
                {
                    if (node.Name == null || node.FirstChild == null)
                    {
                        continue;
                    }
                    if (node.Name == "ItemGroup" && node.FirstChild.Name == "Compile")
                    {
                        XmlNode n = node.FirstChild.CloneNode(true);
                        n.Attributes["Include"].Value = csPath;

                        foreach (XmlNode eq in node.ChildNodes)
                        {
                            if (eq.Name == n.Name
                                && eq.Attributes["Include"].Value == n.Attributes["Include"].Value)
                            {
                                return;
                            }
                        }

                        node.AppendChild(n);
                    }
                }

            }
            xml.Save(projPath);
        }

        #endregion

        private static string GetSqlType(string type)
        {
            switch (type)
            {
                case "int":
                    return "MySqlDbType.Int32";
                case "bigint":
                    return "MySqlDbType.Int64";
                case "varchar":
                    return "MySqlDbType.VarChar";
                case "char":
                    return "MySqlDbType.VarChar";
                case "nvarchar":
                    return "MySqlDbType.VarChar";
                case "datetime":
                    return "MySqlDbType.DateTime";
                case "timestamp":
                    return "MySqlDbType.DateTime";
                case "date":
                    return "MySqlDbType.Date";
                case "text":
                    return "MySqlDbType.Text";
                case "bit":
                    return "MySqlDbType.Bit";
                case "byte":
                    return "MySqlDbType.Byte";
                case "double":
                    return "MySqlDbType.Double";
                case "decimal":
                    return "MySqlDbType.Decimal";
                case "float":
                    return "MySqlDbType.Float";
                case "tinyint":
                    return "MySqlDbType.Int16";
                case "smallint":
                    return "MySqlDbType.Int16";
                default:
                    return "MySqlDbType.VarChar";
            }
        }

        private static string GetFiledType(string type)
        {
            switch (type)
            {
                case "tinyint":
                    return "int";
                case "smallint":
                    return "int";
                case "double":
                    return "double";
                case "decimal":
                    return "decimal";
                case "float":
                    return "float";
                case "bit":
                    return "bool";
                case "int":
                    return "int";
                case "bigint":
                    return "long";
                case "varchar":
                    return "string";
                case "char":
                    return "string";
                case "nvarchar":
                    return "string";
                case "datetime":
                    return "DateTime";
                case "timestamp":
                    return "DateTime";
                case "date":
                    return "DateTime";
                case "text":
                    return "string";
                case "mediumint":
                    return "int";
                case "enum":
                    return "int";
                default:
                    return "string";
            }
        }

        private static string GetDefualt(string type)
        {
            switch (type)
            {
                case "tinyint":
                    return "false";
                case "smallint":
                    return "0";
                case "double":
                    return "0.0";
                case "decimal":
                    return "0.0";
                case "float":
                    return "0.0";
                case "bit":
                    return "0";
                case "int":
                    return "0";
                case "bigint":
                    return "0";
                case "varchar":
                    return "";
                case "char":
                    return "";
                case "nvarchar":
                    return "";
                case "datetime":
                    return "2016-1-1";
                case "timestamp":
                    return "1451581261";
                case "date":
                    return "2016-1-1";
                case "text":
                    return "";
                case "mediumint":
                    return "0";
                case "enum":
                    return "0";
                default:
                    return "";
            }            
        }
    }
}
